import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export enum PreferenceKey {
  MAINSIDERLOCKKEY = 'main:sider:lock',
}

const initialState: {
  loading: boolean;
  error: any;
  token: string;
  secretKey: string;
  tenantId: number;
  organizeId?: number;
  organizes: any[];
  userToken: any;
  user: any;
  preference: any;
} = {
  loading: false,
  error: null,
  token: '',
  secretKey: '',
  tenantId: -1,
  organizeId: undefined,
  organizes: [],
  userToken: null,
  user: null,
  preference: {},
};

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    catchError: (state, action) => {
      state.error = action.payload.error;
      state.loading = false;
    },
    start: (state) => {
      state.error = null;
      state.loading = true;
    },
    end: (state) => {
      state.loading = false;
    },
    persistToken: (state, action) => {
      state.token = action.payload.token;
      state.secretKey = action.payload.secretKey;
    },
    setTenantId: (state, action) => {
      state.tenantId = action.payload;
    },
    setOrganizeId: (state, action) => {
      state.organizeId = action.payload;
    },
    setOrganizes: (state, action) => {
      const orgs = action.payload;
      state.organizes = orgs;
      state.organizeId = orgs[0].id;
    },
    setUserToken: (state, action) => {
      state.userToken = action.payload;
    },
    setUserInfo: (state, action) => {
      state.user = action.payload;
    },
    updatePreference: (state, action) => {
      state.preference = action.payload;
    },
    userLogout: (state) => {
      localStorage.removeItem(
        `persist:${import.meta.env.VITE_REACT_APP_PERSIST_KEY}`
      );
      Object.keys(initialState).forEach((key: any) => {
        (state as any)[key] = (initialState as any)[key];
      });
    },
  },
});
